import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 倒计时组件
class CountdownWidget extends StatefulWidget {
  /// 倒计时间，单位秒
  final int num;

  /// 倒计时结束时执行的操作
  final Function() endFun;

  const CountdownWidget({super.key, required this.num, required this.endFun});

  @override
  State<CountdownWidget> createState() => _CountdownWidgetState();
}

class _CountdownWidgetState extends State<CountdownWidget> {
  /// 倒计时显示
  late String timeShow;

  /// 倒计时工具类
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    timeShow = "${widget.num}秒";
    // 开始倒计时
    _startCountdown();
  }

  @override
  void dispose() {
    super.dispose();
    // 取消计时器
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      timeShow,
      style: FontUtil.fontGrey5(16),
    );
  }

  /// 开始倒计时
  void _startCountdown() {
    int count = widget.num;
    // 循环执行，间隔1秒
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // 自减
      count--;
      // 判断是否结束
      if (count < 1) {
        _timer.cancel();
        widget.endFun();
      }
      // 更新时间
      String sec = _secondsFormat(count);
      setState(() {
        timeShow = "$sec秒";
      });
    });
  }

  /// 将秒数格式化 1 -> 01
  _secondsFormat(int seconds) {
    String sec = seconds.toString();
    if (seconds < 10) {
      sec = "0$seconds";
    }
    return sec;
  }
}
